<template>
    <ex-dialog
      width="880px"
      class="ex-diolog"
      :title="title"
      :visible="visible"
      :close-on-click-modal="false"
      @closeDialog="handleClose"
    >
      <div class="main" v-loading="loading">
        <template>
          <el-form :model="ruleForm" :rules="rules" ref="ruleForm" :label-width="labelWidth" class="demo-ruleForm">
            <el-form-item label="服务项目：" prop="serviceItemName">
              <el-input placeholder="请输入" v-model="ruleForm.serviceItemName" maxlength="50" show-word-limit style="width: 530px;" :disabled="itemType=='1'?true:false"></el-input>
            </el-form-item>
            <el-form-item label="该项目是否记入服务次数：" prop="addServiceCountType">
              <el-radio v-model="ruleForm.addServiceCountType" label="1" :disabled="itemType=='1'?true:false">是</el-radio>
              <el-radio v-model="ruleForm.addServiceCountType" label="2" :disabled="itemType=='1'?true:false">否</el-radio>
            </el-form-item>
            <el-form-item label="" prop="serviceCountType" v-if="ruleForm.addServiceCountType=='1'" >
              <el-select v-model="ruleForm.serviceCountType" @change="serviceCountChange" filterable placeholder="请选择" style="width: 200px;" :disabled="itemType=='1'?true:false">
                  <el-option v-for="item in serviceCountTypeOptions" :key="item.id" :label="item.value" :value="item.id"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="服务项目状态：" prop="status" required>
              <el-switch v-model="ruleForm.status" active-text="开启" inactive-text="关闭" :active-value="'1'" :inactive-value="'2'" :disabled="itemType=='1'?true:false"></el-switch>
            </el-form-item>
            <el-form-item label="服务环节：" required>
              <div class="list_box" v-for="(item,index) in ruleForm.linkList" :key="index">
                <el-form-item :label="'服务环节' + (index+1) + '名称：'" :label-width="linkLabel" :prop="'linkList.' + index + '.serviceItemLinkName'" :rules="rules.serviceItemLinkName" >
                    <el-input placeholder="请输入" v-model="item.serviceItemLinkName" maxlength="50" show-word-limit :style="{width: inputWidth}" />
                </el-form-item>
                <el-form-item label="负责人类型：" :prop="'linkList.' + index + '.authorityType'" :rules="rules.authorityType" :label-width="linkLabel" style="margin: 20px 0;">
                  <el-select v-model="item.authorityType" filterable placeholder="请选择" @change="authorityTypeChange($event,item,index)" :style="{width: inputWidth}">
                      <el-option v-for="items in authorityTypeOptions" :key="items.id" :label="items.value" :value="items.id"></el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="选择负责人：" v-if="item.authorityType!='1' && item.authorityType!='7'" :prop="'linkList.' + index + '.responsiblePersonId'" :rules="rules.responsiblePersonId" :label-width="linkLabel">
                  <el-select v-model="item.responsiblePersonId" filterable placeholder="请选择" clearable :style="{width: inputWidth}">
                      <el-option v-for="items in item.personOptions" :key="index + items.id" :label="items.name + '(' + items.phoneNumber + ')'" :value="items.id"></el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="直播环节操作事项：" v-if="(ruleForm.serviceCountType=='1'||ruleForm.serviceCountType=='2')&&ruleForm.addServiceCountType=='1'" :prop="'linkList.' + index + '.childBusinessType'" :rules="rules.childBusinessType" :label-width="linkLabel" style="margin: 20px 0 0;">
                  <el-select v-model="item.childBusinessType" filterable placeholder="请选择" :style="{width: inputWidth}">
                      <el-option v-for="items in childBusinessTypeLs" :key="index + items.id" :label="items.value" :value="items.id"></el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="短视频环节操作事项：" v-if="(ruleForm.serviceCountType=='3'||ruleForm.serviceCountType=='4'||ruleForm.serviceCountType=='5')&&ruleForm.addServiceCountType=='1'" :prop="'linkList.' + index + '.childBusinessType'" :rules="rules.childBusinessType" :label-width="linkLabel" style="margin: 20px 0 0;">
                  <el-select v-model="item.childBusinessType" filterable placeholder="请选择" :style="{width: inputWidth}">
                      <el-option v-for="items in shortVideoTypeLs" :key="index + items.id" :label="items.value" :value="items.id"></el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="环节说明" :label-width="linkLabel" style="margin: 20px 0 0;">
                    <el-input placeholder="请输入" type="textarea" v-model="item.description" maxlength="500" show-word-limit :autosize="{ minRows: 4, maxRows: 6}" :style="{width: inputWidth}" />
                </el-form-item>
                <div class="delete_box">
                  <span @click="deletLink(index)" v-if="index!=0">删除</span>
                </div>
              </div>
              <div class="addService" @click="addView" v-if="ruleForm.linkList.length<10&&itemType!='1'">添加服务环节</div>
            </el-form-item>
          </el-form>
        </template>
      </div>
      <div class="button_box">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" :loading="AgreeLoading" @click="submitForm('ruleForm')">
          <span v-if="pathType =='add'">保存</span>
          <span v-if="pathType == 'edit'">确认</span>
        </el-button>
      </div>
    </ex-dialog>
  </template>
  <script>
  import Loading from "@/components/Loading/index";
  // api
  import {
    personList,addServiceLink,editServiceLink,serviceLinkDetail
  } from "@/api/customer/serviceManage";
  export default {
    components: {
      Loading,
    },
    props: {
      visible: Boolean,
      id: String,
      pathType: String,
    },
    data() {
      return {
        labelWidth: "190px",
        inputWidth: "400px",
        linkLabel:"170px",
        title: "新增/编辑服务项目",
        loading: false,
        disabled: false,
        AgreeLoading: false,
        ruleForm: {
          addServiceCountType:'1',//是否记入服务次数类型 1 是 2否
          serviceCountType:'',//1记入短视频服务次数 2 记入直播服务次数
          serviceItemName:'',//服务项目
          status:'1',//状态 1正常 2停用
          linkList:[ //服务环节数据集合
            {
              authorityType:'',//负责人类型 1 客户负责人 2 组品负责人 3 排期负责人 4 服务负责人 5 物料负责人
              responsiblePersonId:'',//负责人id
              serviceItemLinkName:'',//服务环节名称
              personOptions:[],
              childBusinessType:'',// 直播业务（1无特殊操作事项 2 直播排期 3操作填写直播数据）/短视频业务（1无特殊操作事项 2填写短视频数量）
              description:'',//环节说明
            }
          ]
        },
        rules: {
          serviceItemName: [
            { required: true,message: "请输入服务项目",trigger: ["change", "bulr"]}
          ],
          addServiceCountType: [
            { required: true,message: "请选择",trigger: ["change", "bulr"]}
          ],
          serviceCountType: [
            { required: true,message: "请选择",trigger: ["change", "bulr"]}
          ],
          serviceItemLinkName: [
            { required: true,message: "请输入服务环节名称",trigger: ["change", "bulr"]}
          ],
          authorityType: [
            { required: true,message: "请选择负责人类型",trigger: ["change", "bulr"]}
          ],
          // responsiblePersonId: [
          //   { required: true,message: "请选择负责人",trigger: ["change", "bulr"]}
          // ],
          childBusinessType: [
            { required: true,message: "请选择环节操作事项",trigger: ["change",]}
          ],
        },
        serviceCountTypeOptions:[], //服务项目记入服务类型字典
        authorityTypeOptions:[],//负责人类型字典
        itemType:'2',//项目类型 1 初始化项目 2 自定义项目
        childBusinessTypeLs:[],//直播环节操作事项
        shortVideoTypeLs:[],//短视频环节操作事项
      };
    },
    computed: {},
    created() {
      this.getDict()
      if(this.pathType=='edit'){
        this.title = '编辑服务项目'
        this.getDetail()
      }else{
        this.title = '新增服务项目'
      }
    },
    mounted() {
     
    },
    computed: {},
    methods: {
      //获取状态字典
      getDict() {
        var dictType = "service_count_type,responsible_person_authority_type,bee_child_business_type,bee_child_business_video_type";
        this.$getSelectList(dictType)
          .then((res) => {
            this.serviceCountTypeOptions = res.result[0].dictList
            this.authorityTypeOptions = res.result[1].dictList
            this.childBusinessTypeLs = res.result[2].dictList
            this.shortVideoTypeLs = res.result[3].dictList
          })
      },
      //查询负责人下拉框列表
      getPersonList(id,index) {
        let list = []
        let data = {
          type: id
        }
        return new Promise((resolve, reject) => {
          personList(data).then((res) => {
            list = res.result
            resolve(list)
              // this.ruleForm.linkList[index].personOptions = res.result
              // this.ruleForm.linkList[index].responsiblePersonId = ''
          })
        });
      },
      //获取详情
      getDetail(){
        var id = this.id
        this.loading = true
        serviceLinkDetail(id).then( res => {
          this.itemType = res.result.itemType
          let linkList = res.result.linkList
          linkList.forEach(async (item,index)=>{
            item.personOptions = await this.getPersonList(item.authorityType,index)
          })
          this.ruleForm = {
              id: this.id,
              linkList: linkList,
              addServiceCountType: res.result.addServiceCountType,//是否记入服务次数类型 1 是 2否
              serviceCountType: res.result.serviceCountType,//1记入短视频服务次数 2 记入直播服务次数
              serviceItemName: res.result.serviceItemName,//服务项目
              status: res.result.status,//状态 1正常 2停用
            }
            setTimeout(()=>{
              this.$forceUpdate()
              this.loading = false
            },1000)
        }).catch(()=>{
          this.loading = false
        })
      },
      //添加服务环节
      addView(){
        var obj = {
          authorityType:'',//负责人类型 1 客户负责人 2 组品负责人 3 排期负责人 4 服务负责人 5 物料负责人
          responsiblePersonId:'',//负责人id
          serviceItemLinkName:'',//服务环节名称
          personOptions:[],
          childBusinessType:'',//直播业务（1无特殊操作事项 2 直播排期 3操作填写直播数据）/短视频业务（1无特殊操作事项 2填写短视频数量）
          description:'',//环节说明
        }
        this.ruleForm.linkList.push(obj)
      },
      /* 删除环节 */
      deletLink(index) {
        this.ruleForm.linkList.splice(index, 1)
      },
      //负责人类型选择
      async authorityTypeChange(e,item,index){
        this.ruleForm.linkList[index].personOptions = await this.getPersonList(e,index)
        this.ruleForm.linkList[index].responsiblePersonId = ''
      },
      //服务项目类型选择时 清空环节操作事项
      serviceCountChange(){
        this.ruleForm.linkList.forEach((item,index)=>{
          item.childBusinessType = ''
          this.$nextTick(()=>{
            this.$refs.ruleForm.clearValidate(['linkList.'+index+'.childBusinessType']);
          })
        })
      },
      //取消
      handleClose(formName) {
        this.$emit("update:visible", false);
      },
      submitForm(formName) {
        //创建确定
        this.$refs[formName].validate(valid => {
          if (valid) {
            this.AgreeLoading = true
            var data = {
              ...this.ruleForm
            }
            if(this.pathType == 'add'){
              addServiceLink(data).then(res => {
                this.handleClose()
                this.$message.success('保存成功')
                this.$emit('success')
                this.AgreeLoading = false
              }).catch(()=>{
                this.AgreeLoading = false
              })
            }else if(this.pathType == 'edit'){
              editServiceLink(data).then(res => {
                this.handleClose()
                this.$message.success('修改成功')
                this.$emit('success')
                this.AgreeLoading = false
              }).catch(()=>{
                this.AgreeLoading = false
              })
            }
            
            
          } else {
            console.log("error submit!!");
            return false;
          }
        });
      },
    }
  };
  </script>
  <style lang="scss" scoped>
  .ex-diolog {
    ::v-deep .ex--dialog--footer {
      border: none !important;
      padding: 0 !important;
    }
  
    ::v-deep .ex--dialog--main {
      padding: 10px 20px !important;
    }
  }
  .el-select,.el-input,.el-cascader{
    width: 400px;
  }
  .main {
    padding: 20px 20px;
  }
  .button_box{
    display: flex;
    justify-content: center;
  }
  .list_box{
    border: 1px solid #ddd;
    border-radius: 10px;
    padding: 10px 0;
    margin-bottom: 20px;
  }
  .addService{
    width: 540px;
    height: 30px;
    background-color: #1890ff;
    border-radius: 6px;
    color: #FFFFFF;
    line-height: 30px;
    text-align: center;
    cursor: pointer;
  }
  .addService:hover{
    opacity: 0.8;
  }
  .delete_box{
    color: #fc3131;
    width: 100%;
    text-align: right;
    padding: 10px 20px 0 0;
  }
  .delete_box span{
    cursor: pointer;
  }
  .delete_box span:hover{
    opacity: 0.8;
  }
  </style>
  